import { defineStore } from 'pinia';
import { MessagePlugin } from 'tdesign-vue-next';
import { TOKEN_NAME } from '@/config/global';
import { store } from '@/store';
import { getMenus } from '@/api/menus';
import { asyncRouterList } from '@/router';

const InitMenusInfo = {
  menuList: [],
  menuSpredList: [],
};

export const menusStore = defineStore('menus', {
  state: () => ({
    token: localStorage.getItem(TOKEN_NAME) || 'main_token', // 默认token不走权限
    menusInfo: { ...InitMenusInfo },
  }),
  getters: {
    menuList: (state) => {
      return state.menusInfo?.menuList;
    },
  },
  actions: {
    async getMenus() {
      try {
        const res = await getMenus(this.token);
        const pushRouter = asyncRouterList;
        generaMenu(pushRouter, res.data);

        this.menusInfo.menuList = pushRouter;
      } catch (e) {
        MessagePlugin.error('菜单获取失败');
      }
    },
  },
  persist: false,
});

export function getMenusStore() {
  return menusStore(store);
}

// 动态菜单还是定义在前端，后台只会返回有权限的菜单列表，通过遍历服务端的菜单数据，没有的将对于菜单进行隐藏
// 这样的好处是服务端无需返回前端菜单相关结构，并且菜单显示又可以通过服务端来控制，进行菜单的动态控制
// 前端新增页面也无需先通过服务端进行菜单添加，遵循了前后端分离原则
export function generaMenu(routes, srvMenus) {
  for (let i = 0; i < routes.length; i++) {
    const routeItem = routes[i];
    let showItem = false;
    for (let j = 0; j < srvMenus.length; j++) {
      const srvItem = srvMenus[j];

      if (routeItem.srvName !== undefined && routeItem.srvName === srvItem.srvName) {
      }

      // 前后端数据通过 srvName 属性来匹配
      if (routeItem.srvName !== undefined && routeItem.srvName === srvItem.srvName && srvItem.show === true) {
        showItem = true;
        routes[i].meta.hidden = false;
        break;
      }
    }

    if (showItem === false) {
      routes[i].meta.hidden = true;
    }

    if (routeItem.children !== undefined && routeItem.children.length > 0) {
      generaMenu(routes[i].children, srvMenus);
    }
  }
}
